<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="9">
                    <el-input placeholder="请输入内容" v-model="query" clearable @clear="searchAllValue">
                        <el-button slot="append" icon="el-icon-search" @click="searchValue"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUserDialog=true">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table
                :data="usersListData"
                border stripe
                style="width: 100%">
                <el-table-column
                    label="#"
                    type="index">
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="用户名">
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色名">
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="手机号">
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱">
                </el-table-column>
                <el-table-column
                    prop="mg_state"
                    label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作" width="180px">
                    <template slot-scope="scope">
                        
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="eidtUser(scope.row.id)"></el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUserById(scope.row.id)"></el-button>
                        <el-tooltip class="item" effect="dark" content="分配角色" :enterable="false" placement="top">
                            <el-button type="warning " size="mini" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagenum"
                :page-sizes="[1, 2, 5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addUserDialog"
            width="50%"
            @close="closeAddUserForm"
        >
            <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input  v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input  v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialog = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog
        title="修改用户"
        :visible.sync="editUserDialog"
        width="50%"
        @close="closeEditUserForm">
            <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editUserForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editUserDialog = false">取 消</el-button>
                <el-button type="primary" @click="updataUser">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="分配角色"
            :visible.sync="setRoleVisible"
            width="50%"
            @close="closeAuthName"
            >
            <div>
                <p class="mb10">当前用户名：{{userInfo.username}}</p>
                <p class="mb10">当前角色名：{{userInfo.role_name}}</p>
                <p class="mb10">分配角色：
                    <el-select v-model="authName" placeholder="请选择">
                        <el-option
                        v-for="item in getRolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRoleById">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script lang="ts">
    import {apiAddress} from "@/utils/apiAddress";
    import {Component,Vue, Provide} from "vue-property-decorator";
    @Component({})
    export default class Login extends Vue{
        checkEmail=(rule:any, value:any, callback:Function) => {
            var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(reg.test(value)){
                return callback()
            }
            return callback(new Error('请输入正确的邮箱'))
        }
        checkMobile=(rule:any, value:any, callback:Function) => {
            var reg =/^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
            if(reg.test(value)){
                return callback()
            }
            return callback(new Error('请输入正确的手机号'))
        }
        query:String="";
        pagenum:Number=1;
        pagesize:Number=2;
        total:Number=0;
        usersListData:[]=[];
        addUserDialog:boolean= false;
        addUserForm:{
            username:String;
            password:String;
            email:String;
            mobile:String;
        }={
            username:"",
            password:"",
            email:"",
            mobile:""
        }
        addUserRules={
            username:[
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
            ],
            password:[
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
            ],
            email:[
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: this.checkEmail, trigger: 'blur' }
            ],
            mobile:[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: this.checkMobile, trigger: 'blur' }
            ]
        }
        editUserDialog:boolean= false
        editUserForm:{
            username:String,
            email:String,
            mobile:String,
            id:Number
        }={
            username:"",
            email:"",
            mobile:"",
            id:0
        }
        editUserRules={
            username:[
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
            ],
            email:[
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { validator: this.checkEmail, trigger: 'blur' }
            ],
            mobile:[
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { validator: this.checkMobile, trigger: 'blur' }
            ]
        }
        userInfo:any={}
        getRolesList:[]=[]
        setRoleVisible:boolean= false
        authName:String=""
        created(){
            this.usersList();
            this.getRoles();
        }
        closeAuthName(){
            this.authName=""
            this.userInfo={}
        }
        async setRoleById(){
            if(!this.authName){
                return this.$message.error("请选择用户角色");
            }
            const data={
                id:this.userInfo.id,
                rid:this.authName
            }
            const res=await apiAddress.setUsersRole(data);
            if(res.meta.status!=200) return this.$message.error(res.meta.msg);
            this.usersList();
            this.setRoleVisible=false
        }
        async getRoles() {
            let data={}
            const res= await apiAddress.getRoles(data);
            if(res.meta.status!=200) return this.$message.error(res.meta.msg);
            this.getRolesList=res.data
        }
        setRole(info:any){
            this.userInfo=info
            this.setRoleVisible=true
        }
        async deleteUserById(id:Number){
            const confirmRes=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error=>error)
            if(confirmRes=="confirm"){
                const res=await apiAddress.deleteUserById({id:id});
                if(res.meta.status!=200) return this.$message.error(res.meta.msg);
                this.usersList();
            }else{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });   
            }
            
        }
        async eidtUser(id:Number){
            this.editUserForm.id=id;
            const res=await apiAddress.getUsersById({id:id})
            if(res.meta.status!=200) return this.$message.error(res.meta.msg);
            this.editUserForm.username=res.data.username
            this.editUserForm.mobile=res.data.mobile
            this.editUserForm.email=res.data.email
            this.editUserDialog=true

        }
        closeEditUserForm(){
            (this.$refs.editUserRef as any).resetFields();
        }
        updataUser(){
            
            (this.$refs.editUserRef as any).validate(async (valid:boolean)=>{
                if(!valid) return;
                const res=await apiAddress.putUsers({id:this.editUserForm.id,email:this.editUserForm.email,mobile:this.editUserForm.mobile});
                if(res.meta.status!=200) return this.$message.error(res.meta.msg);
                this.editUserDialog=false
                this.usersList();
            })
        }
        addUser(){
            (this.$refs.addUserRef as any).validate(async (valid:boolean)=>{
                if(!valid) return;
                const res=await apiAddress.addUsers(this.addUserForm);
                if(res.meta.status!=201) return this.$message.error(res.meta.msg);
                this.addUserDialog=false
                this.usersList();
            })
        }
        //关闭表单重置验证
        closeAddUserForm(){
            (this.$refs.addUserRef as any).resetFields();
        }
        searchAllValue(){
            this.usersList();
        }
        searchValue(){
            this.usersList();
        }
        async changeState(info:any){
            let data={
                uId:info.id,
                type:info.mg_state
            }
            const res=await apiAddress.changeUserStatus(data);
            if(res.meta.status!=200){
                info.mg_state=!info.mg_state
                return this.$message.error(res.meta.msg);
            } 
            this.$message.success(res.meta.msg);
        }
        handleSizeChange(newSize:Number){
            this.pagesize=newSize
            this.usersList();
        }
        handleCurrentChange(newPage:Number){
            this.pagenum=newPage
            this.usersList();
        }
        async usersList() {
            let data={
                query:this.query,
                pagenum:this.pagenum,
                pagesize:this.pagesize
            }
            const res= await apiAddress.usersList(data);
            if(res.meta.status!=200) return this.$message.error(res.meta.msg)
            this.usersListData=res.data.users
            this.total=res.data.total
        }
    }
</script>

<style scoped>
.mb10{
    margin-bottom: 10px;
}
</style>